﻿using System;
using System.Linq;
using Colligate;

namespace OrgDataSource
{
// ReSharper disable InconsistentNaming
    public class GroupDS:IOrgDS
// ReSharper restore InconsistentNaming
    {
        #region\\delete
        public int DeleteTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context)
        {
            switch (dataType.ToLower())
            {
                case "group": return DeleteGroup(dataGuid, context);
                case "groupmember": return DeleteGroupMember(dataGuid, context);
                default: throw new Exception("GroupDS无法处理该" + dataType + "的数据");
            }
        }

        private static int DeleteGroup(string dataGuid, orgEntities context)
        {
            System.Data.Common.DbTransaction trans = null;
            try
            {
                context.Connection.Open();
                trans = context.Connection.BeginTransaction();
                var group = context.Group.FirstOrDefault(cc => cc.Guid == dataGuid);
                context.DeleteObject(group);
                var groupMember = context.GroupMember.Where(cc => cc.GroupGuid == dataGuid).ToList();
                foreach (var item in groupMember)
                    context.DeleteObject(item);
                context.SaveChanges();
                trans.Commit();
                return 0;
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw new Exception("删除数据标识为：" + dataGuid + "的Group数据时出错！");
            }
            finally
            {
                context.Connection.Close();
            }

        }

        private static int DeleteGroupMember(string dataGuid, orgEntities context)
        {
            try
            {
                var groupmember = context.GroupMember.FirstOrDefault(cc => cc.Guid == dataGuid);
                context.DeleteObject(groupmember);
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("删除数据标识为：" + dataGuid + "的GroupMember数据时出错！");
            }
        }
        #endregion
        #region\\get
        public System.Xml.XmlNode GetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context, BaseTaskDataSource baseInfo)
        {
            switch (dataType.ToLower())
            {
                case "group": return GetGroup(dataGuid, context);
                case "groupmember": return GetGroupMember(dataGuid, context);
                case "grouplist": return GetGroupList(dataGuid, context);
                case "groupmemberlist": return GetGroupMemberList(dataGuid, context);
                default: throw new Exception("GroupTask无法处理该" + dataType + "的数据");
            }
        }

        private static System.Xml.XmlNode GetGroup(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "Group");
                var group = context.Group.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new Group
                                                                                           {
                                                                                               Guid = string.Empty,
                                                                                               Name = string.Empty,
                                                                                               Descript = string.Empty
                                                                                           };
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), group.Guid);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), group.Name);
                XmlNodeManage.SetSubValue(result, "Descript", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), group.Descript);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的Group数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetGroupMember(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "GroupMember");
                var groupmember = context.GroupMember.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new GroupMember
                                                                                                       {
                                                                                                           Guid = string.Empty,
                                                                                                           GroupGuid = string.Empty,
                                                                                                           MemberGuid = string.Empty,
                                                                                                           Type = string.Empty,
                                                                                                           Name = string.Empty,
                                                                                                           Status = string.Empty,
                                                                                                           Sort = null
                                                                                                       };
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.Guid);
                XmlNodeManage.SetSubValue(result, "GroupGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.GroupGuid);
                XmlNodeManage.SetSubValue(result, "MemberGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.MemberGuid);
                XmlNodeManage.SetSubValue(result, "Type", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.Type);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.Name);
                XmlNodeManage.SetSubValue(result, "Status", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), groupmember.Status);
                XmlNodeManage.SetSubValue(result, "Order", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), groupmember.Sort);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的GroupMember数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetGroupList(string dataGuid, orgEntities context)
        {
            try
            {
                if (dataGuid != "277b393f-6559-4f79-aa2b-7602d88f8849")
                    throw new Exception("获取的GroupList数据时出错！数据标识不正确");
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "GroupList");
                var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                var group = context.Group;
                foreach (var item in group)
                {
                    var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                    XmlNodeManage.SetSubValue(childNode, "@GUID", item.Guid);
                    XmlNodeManage.SetSubValue(childNode, "@NAME", item.Name);
                    XmlNodeManage.SetSubValue(childNode, "@OUType", "Group");
                    XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", item.Guid);
                    subNode.AppendChild(childNode);
                }
                result.AppendChild(subNode);
                return result;
            }
            catch
            {
                throw new Exception("获取的GroupList数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetGroupMemberList(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "GroupMemberList");
                var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                var branchList = context.Branch.ToList();
                var applist = context.Application.ToList();
                var memberlist = context.Member.ToList();
                var groupMember = context.GroupMember.Where(cc => cc.GroupGuid == dataGuid && cc.Status == "true").OrderByDescending(cc => cc.Sort);
                foreach (var item in groupMember)
                {
                    var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                    var companyGuid = string.Empty;
                    XmlNodeManage.SetSubValue(childNode, "@GUID", item.MemberGuid);
                    XmlNodeManage.SetSubValue(childNode, "@NAME", item.Name);
                    XmlNodeManage.SetSubValue(childNode, "@OUType", item.Type);
                    if (item.Type.ToLower().Equals("application"))
                        companyGuid = null == applist.FirstOrDefault(cc => cc.Guid == item.MemberGuid)
                                          ? string.Empty
                                          : applist.FirstOrDefault(cc => cc.Guid == item.MemberGuid).CompanyGuid;
                    if (item.Type.ToLower().Equals("company"))
                        companyGuid = item.MemberGuid;
                    if (item.Type.ToLower().Equals("branch"))
                        companyGuid = null == branchList.FirstOrDefault(cc => cc.Guid == item.MemberGuid)
                                          ? string.Empty
                                          : branchList.FirstOrDefault(cc => cc.Guid == item.MemberGuid).CompanyGuid;
                    if (item.Type.ToLower().Equals("member"))
                    {
                        var branchGuid = null == memberlist.FirstOrDefault(cc => cc.Guid == item.MemberGuid)
                                             ? string.Empty
                                             : memberlist.FirstOrDefault(cc => cc.Guid == item.MemberGuid).BranchGuid;
                        companyGuid = Utility.GetCompanyGuid(branchGuid, branchList);
                    }
                    XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", companyGuid);
                    childNode.InnerText = item.Guid;
                    subNode.AppendChild(childNode);
                }
                result.AppendChild(subNode);
                return result;
            }
            catch
            {
                throw new Exception("获取GroupMemberList数据时出错！");
            }
        }
        #endregion
        #region\\set
        public int SetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, System.Xml.XmlNode xmlData, orgEntities context)
        {
            var datatype = XmlNodeManage.GetSubValue(xmlData, "@DataType");
            switch (datatype.ToLower())
            {
                case "group": return SetGroup(xmlData, context);
                case "groupmember": return SetGroupMember(xmlData, context);
                default:throw new Exception("GroupTask无法处理该" + datatype + "的数据");
            }
        }

        private static int SetGroup(System.Xml.XmlNode xmlData, orgEntities context)
        {
            try
            {
                var id = Utility.CheckXmlData(xmlData,"Guid");
                var group = context.Group.FirstOrDefault(cc => cc.Guid == id);
                if (null == group)
                {
                    group = new Group
                                {
                                    Guid = id,
                                    Name = Utility.CheckXmlData(xmlData, "Name"),
                                    Descript = Utility.CheckXmlData(xmlData, "Descript")
                                };
                    context.AddToGroup(group);
                }
                else
                {
                    group.Name = Utility.CheckXmlData(xmlData, "Name");
                    group.Descript = Utility.CheckXmlData(xmlData, "Descript");
                }
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("写入Group数据时出错！");
            }
        }

        private static int SetGroupMember(System.Xml.XmlNode xmlData, orgEntities context)
        {
            try
            {
                var id = Utility.CheckXmlData(xmlData,"Guid");
                var groupmember = context.GroupMember.FirstOrDefault(cc => cc.Guid == id);
                if (null == groupmember)
                {
                    groupmember = new GroupMember
                                      {
                                          Guid = id,
                                          GroupGuid = Utility.CheckXmlData(xmlData, "GroupGuid"),
                                          MemberGuid = Utility.CheckXmlData(xmlData, "MemberGuid"),
                                          Type = Utility.CheckXmlData(xmlData, "Type"),
                                          Status = Utility.CheckXmlData(xmlData, "Status"),
                                          Name = Utility.CheckXmlData(xmlData, "Name"),
                                          Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order"))
                                      };
                    context.AddToGroupMember(groupmember);
                }
                else
                {
                    groupmember.GroupGuid = Utility.CheckXmlData(xmlData, "GroupGuid");
                    groupmember.MemberGuid = Utility.CheckXmlData(xmlData, "MemberGuid");
                    groupmember.Type = Utility.CheckXmlData(xmlData, "Type");
                    groupmember.Status = Utility.CheckXmlData(xmlData, "Status");
                    groupmember.Name = Utility.CheckXmlData(xmlData, "Name");
                    groupmember.Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order"));
                }
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("写入GroupMember数据时出错！");
            }
        }
        #endregion
        #region\\transform
        public System.Xml.XmlNode TransformTaskData(OUDataInfo userInfo, System.Xml.XmlNode xmlParam, orgEntities context, BaseTaskDataSource baseInfo)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
